package com.wyq.config;

import com.wyq.domain.LoginUser;
import com.wyq.domain.User;
import com.wyq.utils.JwtUtil;
import com.wyq.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(Objects.isNull(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userid;
        try{
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userid);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        // 获取权限信息封装到Authentication中
        //该方法三个参数的内部实现了设置已认证状态，可以跳过后续过滤器 上面放行没认证故后续过滤器还要执行
        UsernamePasswordAuthenticationToken upat =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(upat);
        //放行
        filterChain.doFilter(request,response);
    }
}
